#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
using namespace std;

void SetNonblock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        cerr << "fcntl" << endl;
        return;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
    cout << "set " << fd << " nonblock success" << endl;
}

int main()
{
    char buff[1024];
    SetNonblock(0);
    while (true)
    {
        ssize_t n = read(0, buff, sizeof(buff) - 1);
        // 如果接收成功
        if (n > 0)
        {
            buff[n - 1] = 0;
            cout << "buffer get : " << buff << endl;
        }
        // 如果结束
        else if (n == 0)
        {
            cout << "read done" << endl;
            break;
        }
        else
        {
            cerr << "read error"
                 << ", n : " << n << ", error : " << errno << " , strerror : " << strerror(errno) << endl;
            sleep(1);
        }
    }
    return 0;
}